package com.eastseeway.radioproject.gmn;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.eastseeway.radioproject.R;
import com.eastseeway.radioproject.base.BaseActivity;
import com.eastseeway.radioproject.base.Const;
import com.eastseeway.radioproject.databinding.ActivityNpactivityBinding;
import com.eastseeway.radioproject.databinding.ItemShortcutInfoBinding;
import com.eastseeway.radioproject.engineer.EngineerActivity;
import com.eastseeway.radioproject.entities.Bean1FromHandle;
import com.eastseeway.radioproject.entities.BeanFromBottomBoard;
import com.eastseeway.radioproject.entities.BeanFromEnergyBoard;
import com.eastseeway.radioproject.entities.MessageEvent;
import com.eastseeway.radioproject.entities.OperationParams;
import com.eastseeway.radioproject.main.DeviceStatus;
import com.eastseeway.radioproject.test.TestActivity;
import com.eastseeway.radioproject.utils.AnimUtils;
import com.eastseeway.radioproject.utils.ByteUtil;
import com.eastseeway.radioproject.utils.CommandGenerator;
import com.eastseeway.radioproject.utils.SPHelper;
import com.eastseeway.radioproject.views.wheel.WheelPicker;
import com.google.gson.Gson;
import com.king.view.arcseekbar.ArcSeekBar;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import struct.StructException;

/*
* 无负压的手柄
* */
public class NPActivity extends BaseActivity<ActivityNpactivityBinding, NPViewModel> {
    private boolean isAccept = true,isElectrodeDetected = false;
    private ShortcutInfoAdapter mShortcutInfoAdapter;
    private final List<Integer> mShortcutList = Arrays.asList(R.mipmap.icon_radio_pre_1,R.mipmap.icon_radio_pre_2,R.mipmap.icon_radio_pre_3,R.mipmap.icon_radio_pre_4,R.mipmap.icon_radio_pre_5);
    private final List<Integer> mShortcutLList = Arrays.asList(R.mipmap.icon_radio_pre_l1,R.mipmap.icon_radio_pre_l2,R.mipmap.icon_radio_pre_l3,R.mipmap.icon_radio_pre_l4,R.mipmap.icon_radio_pre_l5);
    private boolean isPreviousBit6HasException = false,isPreviousBit7HasException = false;
    private boolean isInitialized = false;
    private AlertDialog exceptionDialog;
    private boolean isBit6HasException,isPreviousHandleWorking = false;
    private int energyOffset = 5;
    private final int idhpOffset = 10;
    private final int idlpOffset = 30;
    private final int idpOffset = 1;
    /**
     * 控制是否播报异常7 未识别到电极->识别到电极，发生状态变化后再点击待机时会播报，
     */
    private boolean readyToPlaySound7 = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_npactivity;
    }

    @Override
    protected Class<NPViewModel> getVMClass() {
        return NPViewModel.class;
    }

    @Override
    protected void initEvent() {
        mBinding.npShortcut.setLayoutManager(new GridLayoutManager(this,5));

        mShortcutInfoAdapter = new ShortcutInfoAdapter();
        mBinding.npShortcut.setAdapter(mShortcutInfoAdapter);
        mBinding.npStart.setOnClickListener(v->{
            playClickSound();
            if (!isElectrodeDetected) {
                return;
            }
            if (isBit6HasException) {
                return;
            }
            if (Boolean.TRUE.equals(mViewModel.getIsPreMode().getValue())) {
                mViewModel.getIsPreMode().setValue(false);
            }
            mBinding.npWheelLeftPeriod.stopScroll();
            mBinding.npWheelRightDepth.stopScroll();
            new Handler(Looper.getMainLooper()).postDelayed(()->{
                mViewModel.changeWorkState();
            },50);

        });

        mBinding.handle.setOnClickListener(v->{
            mViewModel.queryOperationParams(SPHelper.getCurrentUserInfo(this));
        });

//        mBinding.textView.setText(BuildConfig.VERSION_NAME);
        mBinding.logo.setOnClickListener(v->{
            startActivity(new Intent(this, TestActivity.class));
        });

        mBinding.test.setOnClickListener(v->{
            continuousClick();
        });
        mBinding.back.setOnClickListener(v->{
            playClickSound();
            finish();
        });

        int[] mShaderColors = new int[]{0xFFC3A6FF, 0xFFA158FF};
        mBinding.arcSeekBarEnergy.setProgressColor(mShaderColors);
        mBinding.arcSeekBarEnergy.setOnChangeListener(new ArcSeekBar.OnChangeListener() {
            @Override
            public void onStartTrackingTouch(boolean isCanDrag) {

            }

            @Override
            public void onProgressChanged(float progress, float max, boolean fromUser) {
                Log.e("12121","onProgressChanged:"+fromUser+progress);
                mViewModel.setEnergy((byte) (progress + energyOffset));
                mBinding.arcSeekBarEnergy.setLabelText(String.valueOf((byte) (progress + energyOffset)));
            }

            @Override
            public void onStopTrackingTouch(boolean isCanDrag) {
                playClickSound();
            }

            @Override
            public void onSingleTapUp() {

            }
        });

        mBinding.arcSeekBarIdhp.setProgressColor(mShaderColors);
        mBinding.arcSeekBarIdhp.setOnChangeListener(new ArcSeekBar.OnChangeListener() {
            @Override
            public void onStartTrackingTouch(boolean isCanDrag) {

            }

            @Override
            public void onProgressChanged(float progress, float max, boolean fromUser) {
                mViewModel.getIdhp().setValue((int) (progress + idhpOffset));
                mBinding.arcSeekBarIdhp.setLabelText(String.valueOf((int) (progress + idhpOffset)));
            }

            @Override
            public void onStopTrackingTouch(boolean isCanDrag) {
                playClickSound();
            }

            @Override
            public void onSingleTapUp() {

            }
        });
        mBinding.arcSeekBarIdhp.setProgress(0);

        mBinding.arcSeekBarIdlp.setProgressColor(mShaderColors);
        mBinding.arcSeekBarIdlp.setOnChangeListener(new ArcSeekBar.OnChangeListener() {
            @Override
            public void onStartTrackingTouch(boolean isCanDrag) {

            }

            @Override
            public void onProgressChanged(float progress, float max, boolean fromUser) {
                mViewModel.getIdlp().setValue((int) (progress + idlpOffset));
                mBinding.arcSeekBarIdlp.setLabelText(String.valueOf((int) (progress + idlpOffset)));
            }

            @Override
            public void onStopTrackingTouch(boolean isCanDrag) {
                playClickSound();
            }

            @Override
            public void onSingleTapUp() {

            }
        });
        mBinding.arcSeekBarIdlp.setProgress(0);

        mBinding.arcSeekBarIdp.setProgressColor(mShaderColors);
        mBinding.arcSeekBarIdp.setOnChangeListener(new ArcSeekBar.OnChangeListener() {
            @Override
            public void onStartTrackingTouch(boolean isCanDrag) {

            }

            @Override
            public void onProgressChanged(float progress, float max, boolean fromUser) {
                mViewModel.getIdp().setValue((int) (progress + idpOffset));
                mBinding.arcSeekBarIdp.setLabelText(String.valueOf((int) (progress + idpOffset)));
            }

            @Override
            public void onStopTrackingTouch(boolean isCanDrag) {
                playClickSound();
            }

            @Override
            public void onSingleTapUp() {

            }
        });
        mBinding.arcSeekBarIdp.setProgress(0);

        List<String> wheelLeftData = new ArrayList<>();
        wheelLeftData.add("- -");
        for (int i = 10; i <= 600; i++) {
            wheelLeftData.add(String.valueOf(i));
        }
        mBinding.npWheelLeftPeriod.setData(wheelLeftData);
        mBinding.npWheelLeftPeriod.setOnItemSelectedListener((picker, data, position) -> {
            playClickSound();
            mViewModel.getContinuousDischargePosition().setValue(position);
            mViewModel.getContinuousDischargePeriod().setValue(position == 0?0:Short.valueOf((String) data));
        });

        mBinding.npWheelRightDepth.setOnItemSelectedListener((picker, data, position)->{
            playClickSound();
            mViewModel.getDepthPosition().setValue(position);
            mViewModel.getDepth().setValue((byte)(Float.parseFloat((String)data) * 10));
        });

        mViewModel.getIsIntermittentMode().observe(this, isIntermittentMode -> {
            if (Boolean.TRUE.equals(mViewModel.getIsStandByState().getValue())) {
                setArcSeekBarEnabled(mBinding.arcSeekBarIdp,isIntermittentMode,false);
                setArcSeekBarEnabled(mBinding.arcSeekBarIdlp,isIntermittentMode,false);
                setArcSeekBarEnabled(mBinding.arcSeekBarIdhp,isIntermittentMode,false);
                setWheelPickerEnabled(mBinding.npWheelLeftPeriod,!isIntermittentMode);
            }
        });

        exceptionDialog = new AlertDialog.Builder(this)
                .setMessage("请拔掉治疗电极头固定销")
                .setPositiveButton("确定", (dialog, which) -> {
                    // 确定按钮点击事件
                    try {
                        sendMessage(CommandGenerator.commandToEraseException(Const.ADDRESS_TO_HANDLE_2_DATA_1));
                    } catch (StructException e) {
                        throw new RuntimeException(e);
                    }
                }).create();
    }

    @Override
    protected void loadData() {
//        mBinding.npInfo.setText(isTcpConnected()?"已连接":"未连接");

        mBinding.setViewModel(mViewModel);
//      从数据库中读取用户的快捷操作参数
        mViewModel.queryOperationParams(SPHelper.getCurrentUserInfo(this));

//        setWheelPickerEnabled(mBinding.npWheelPressure,false);
    }

    @Override
    protected void observeData() {
        mViewModel.getOperationParamsList().observe(this, operationParamsList -> {
            Log.e("12121","getOperationParamsList:");
            if (operationParamsList != null && !operationParamsList.isEmpty()) {
                Log.e("12121", isInitialized+" 预置参数哈哈not null " + new Gson().toJson(operationParamsList));
                mShortcutInfoAdapter.setData(operationParamsList);

                if (isInitialized){
                    return;
                }
                for (OperationParams operationParams : operationParamsList) {
                    if (operationParams.getPosition() == Const.POSITION_PREVIOUS_PARAMS && !operationParams.isEmpty()) {
                        Log.e("12121", "position为6有参数 " + new Gson().toJson(operationParams));
                        isInitialized = true;
                        restoreDataAndParams(operationParams);
                        break;
                    }
                }
            }
        });

        mViewModel.getIsWorkingState().observe(this, isWorkingState -> {
            if (!mViewModel.getIsStandByState().getValue()) {
                mBinding.npStart.setText(isWorkingState?"工作":"准备");
            }
        });

        mViewModel.getFrequency().observe(this, freq -> {
            if (freq == 1) {//1MHz下
                energyOffset = 5;//1MHz从能量5开始
                if (getMachineType(this).equals(Const.MACHINE_TYPE_TAISHI)) {
                    mBinding.arcSeekBarEnergy.setMax(25);//台式能量5-30，对应seekBar的0-25，偏移为5
                } else {
                    mBinding.arcSeekBarEnergy.setMax(45);//立式能量5-50，对应seekBar的0-45，偏移为5
                }
                if (mViewModel.getEnergy() < 5){//切换到1MHz时，如果当前能量小于5，说明在2MHz时，设置为3或者4，但是当前最小是5，应该设置为0，但是seekBar的progress相同时，不触发监听，所以+2（+1不行）
                    mBinding.arcSeekBarEnergy.setProgress(5 - energyOffset + 2);
                }else {
                    mBinding.arcSeekBarEnergy.setProgress(mViewModel.getEnergy() - energyOffset);
                }
            }else {
                energyOffset = 3;
                if (getMachineType(this).equals(Const.MACHINE_TYPE_TAISHI)) {
                    mBinding.arcSeekBarEnergy.setMax(12);
                    if (mViewModel.getEnergy() > 15) {
                        mBinding.arcSeekBarEnergy.setProgress(12);
                    }else {
                        mBinding.arcSeekBarEnergy.setProgress(mViewModel.getEnergy() - energyOffset);
                    }
                } else {
                    mBinding.arcSeekBarEnergy.setMax(17);
                    if (mViewModel.getEnergy() > 20){
                        mBinding.arcSeekBarEnergy.setProgress(17);
                    }else {
                        mBinding.arcSeekBarEnergy.setProgress(mViewModel.getEnergy() - energyOffset);
                    }
                }
            }

        });
        mViewModel.getIsStandByState().observe(this, isStandByState -> {
            mViewModel.saveDataToFile("np:isStandByState changed:"+isStandByState);
            mBinding.npStart.setText(isStandByState?"待机":"准备");
            setArcSeekBarEnabled(mBinding.arcSeekBarEnergy,isStandByState,true);
            if (isStandByState) {
                setArcSeekBarEnabled(mBinding.arcSeekBarIdhp,mViewModel.getIsIntermittentMode().getValue(),false);
                setArcSeekBarEnabled(mBinding.arcSeekBarIdlp,mViewModel.getIsIntermittentMode().getValue(),false);
                setArcSeekBarEnabled(mBinding.arcSeekBarIdp,mViewModel.getIsIntermittentMode().getValue(),false);
                setWheelPickerEnabled(mBinding.npWheelLeftPeriod,!mViewModel.getIsIntermittentMode().getValue());
                mViewModel.resetState();
            }else {
                setArcSeekBarEnabled(mBinding.arcSeekBarIdhp, false,false);
                setArcSeekBarEnabled(mBinding.arcSeekBarIdlp, false,false);
                setArcSeekBarEnabled(mBinding.arcSeekBarIdp, false,false);
                setWheelPickerEnabled(mBinding.npWheelLeftPeriod,false);
                // 待机状态进入准备状态后，保存当前的操作参数，以便下次进入后直接使用
                mViewModel.saveQuickOperationParam(SPHelper.getCurrentUserInfo(this),Const.POSITION_PREVIOUS_PARAMS);
//            非待机状态，即准备状态下，发送命令并声音提示
                mViewModel.sendPreCommand();
                if (readyToPlaySound7 && isElectrodeDetected) {
                    playExceptionSound(7);
                    readyToPlaySound7 = false;
                }
            }
            setWheelPickerEnabled(mBinding.npWheelRightDepth,isStandByState);
            mShortcutInfoAdapter.setIsStandBy(isStandByState);
        });
    }

    private void setArcSeekBarEnabled(ArcSeekBar arcSeekBar,boolean enabled,boolean isBig){
        arcSeekBar.setEnabledDrag(enabled);
        arcSeekBar.setEnabledSingle(enabled);
        if (enabled) {
            int[] mShaderColors = new int[]{0xFF5D7DFF, 0xFFA158FF};
            arcSeekBar.setProgressColor(mShaderColors);
            if (isBig) arcSeekBar.setThumbDrawable(R.mipmap.icon_thumb_big);
            else arcSeekBar.setThumbDrawable(R.mipmap.icon_thumb);
        }else {
            arcSeekBar.setProgressColor(getResources().getColor(R.color.purple_dark1));
            arcSeekBar.setThumbDrawable(R.mipmap.icon_thumb_gray);
        }
        arcSeekBar.setLabelTextColor(enabled? getResources().getColor(R.color.purple) : getResources().getColor(R.color.gray_8b8b8a));
    }

    private void setWheelPickerEnabled(WheelPicker wheelPicker, boolean enabled){
        wheelPicker.setEnabled(enabled);
        wheelPicker.setBackground(enabled? getResources().getDrawable(R.mipmap.bg_wheel_enabled) : getResources().getDrawable(R.mipmap.bg_wheel_disabled));
        wheelPicker.setSelectedItemTextColor(enabled? getResources().getColor(R.color.purple) : getResources().getColor(R.color.gray_8b8b8a));
        wheelPicker.setItemTextColor(enabled? getResources().getColor(R.color.white) : getResources().getColor(R.color.gray_8b8b8a));
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void OnEvent(MessageEvent messageEvent){
        if (messageEvent.getCode() == Const.ADDRESS_FROM_HANDLE_2_DATA_1) {
            Bean1FromHandle bean1FromHandle = (Bean1FromHandle) messageEvent.getData();
            byte workState = bean1FromHandle.getWorkState();
            boolean isHandleWorking = (workState & (byte) 0x01) == 1;
            if (isHandleWorking) {
                mViewModel.saveDataToFile("np:handle working data "+new Gson().toJson(bean1FromHandle));
            }
//            根据运行状态设置图片
            mBinding.handle.setSelected(isHandleWorking);
            if (Boolean.TRUE.equals(mViewModel.getIsAutoNeedleMode().getValue())){
                if (Boolean.TRUE.equals(mViewModel.getIsWorkingState().getValue())) {
                    if (!isHandleWorking) {
                        mViewModel.sendHandleCommand();
                    }
                }else {
                    if (isHandleWorking){
                        mViewModel.sendHandleCommand();
                    }
                }
            }

//            if (!isHandleWorking && isPreviousHandleWorking){
//                if (Boolean.FALSE.equals(mViewModel.getIsStandByState().getValue())) {
//                    mViewModel.getIsStandByState().setValue(true);
//                }
//                if (Boolean.TRUE.equals(mViewModel.getIsWorkingState().getValue())) {
//                    mViewModel.getIsWorkingState().setValue(false);
//                }
//            }
            isPreviousHandleWorking = isHandleWorking;

            if ((workState >> 4 & (byte)0x01) == 0) {
                showErrMsg("未识别治疗电极！");
                readyToPlaySound7 = true;
                mBinding.npElectrodeCount.setVisibility(View.GONE);
                mBinding.npReplaceElectrode.setVisibility(View.VISIBLE);
                AnimUtils.startBlink(mBinding.npReplaceElectrode);
                isElectrodeDetected = false;
                if (Boolean.FALSE.equals(mViewModel.getIsStandByState().getValue())) {
                    mViewModel.getIsStandByState().setValue(true);
                    mViewModel.getIsWorkingState().setValue(false);
                }
                return;
            }else {
                isElectrodeDetected = true;
                mBinding.npElectrodeCount.setVisibility(View.VISIBLE);
                mBinding.npReplaceElectrode.setVisibility(View.GONE);
                mBinding.npInfo.setText("");
                if (bean1FromHandle.getElectrode_count()[0] == 0){
                    mBinding.npElectrodeCount.setText("- - -");
                }else {
                    mBinding.npElectrodeCount.setText(ByteUtil.convertByteArrayToASCIIString(bean1FromHandle.getElectrode_count()).substring(1));
                }
            }
//  针头零点故障
            byte exception = bean1FromHandle.getException();
            isBit6HasException = (exception >> 6 & 1) == 1;
            if (isBit6HasException) {
                if (!isPreviousBit6HasException) {
//                    如果上一次没有故障，本次出现，则报故障 语音
                    playExceptionSound(6);
                }
            }
            isPreviousBit6HasException = isBit6HasException;
            if (isBit6HasException){
                showErrMsg("E601");
                return;
            }
//  退针卡滞故障
            boolean isBit7HasException = (exception >> 7 & 1) == 1;
            if (isBit7HasException) {
                if (!isPreviousBit7HasException) {
                    playExceptionSound(7);
                    if (exceptionDialog != null && !exceptionDialog.isShowing()) {
                        exceptionDialog.show();
                    }
                }
            }
            isPreviousBit7HasException = isBit7HasException;

            StringBuilder errInfo = new StringBuilder();
            if ((exception >> 2 & 0x01) == 1) {
                errInfo.append("未吸附: ").append(bean1FromHandle.getPressure());
            }
//            超限故障
            if ((exception >> 1 & 0x01) == 1) {
                mViewModel.saveDataToFile("np:handle exception E701");
                errInfo.append("E701 ");
            }
//            治疗次数用完
            if ((exception & 1) == 1) {
                errInfo.append("治疗电极次数用完 ");
            }
            if (!errInfo.toString().isEmpty()) {
                showErrMsg(errInfo.toString());
            }

            if (bean1FromHandle.getSkinResistance() != -1) {
                mBinding.skinResistance.setText(bean1FromHandle.getSkinResistance()+"");
            }

            int unsignedTotalPower = ((int) bean1FromHandle.getTotalPower()) & 0xFFFF; // 转为无符号 int
            if (Boolean.TRUE.equals(mViewModel.getIsMJ().getValue())) {
                mBinding.totalPower.setText(String.valueOf(unsignedTotalPower));
                mBinding.outputEnergyTitle.setText("输出能量mJ");
            } else {
                mBinding.totalPower.setText(String.format("%.2f", unsignedTotalPower / 1000.0f));
                mBinding.outputEnergyTitle.setText("输出能量J");
            }

            mViewModel.getShengyucishu().setValue(bean1FromHandle.getShengyucishu());
        }else if(messageEvent.getCode() == Const.ADDRESS_FROM_BOTTOM_BOARD){
            if (!mViewModel.getIsStandByState().getValue()){
                BeanFromBottomBoard beanFromBottomBoard = (BeanFromBottomBoard) messageEvent.getData();
                mViewModel.saveDataToFile("np:bottom board working data " + new Gson().toJson(beanFromBottomBoard));
                int devStatus = beanFromBottomBoard.getDev_status();
                int bitMask = 1 << 1;
                if ((bitMask & devStatus) == 2) {//脚踏开关踩下去
                    if (mViewModel.getIsAutoNeedleMode().getValue()) {//自动出针模式
                        if (isAccept){
                            isAccept = false;
                            if (isElectrodeDetected){
                                mViewModel.saveDataToFile("np:Foot switch pressed  auto needle ");
                                mViewModel.getIsWorkingState().setValue(!mViewModel.getIsWorkingState().getValue());
                                mViewModel.sendHandleCommand();
                            }else {
                              playInstallElectrodeSound();
                            }
                        }
                    }else {//脚踏出针模式
                        if (isAccept) {
                            isAccept = false;
                            if (isElectrodeDetected){
                                mViewModel.saveDataToFile("np:Foot switch pressed not auto needle ");
                                mViewModel.getIsWorkingState().setValue(true);
                                mViewModel.sendHandleCommand();
                            }else {
                                playInstallElectrodeSound();
                            }
                        }
                    }
                }else {//脚踏开关释放
                    isAccept = true;
                    if (!mViewModel.getIsAutoNeedleMode().getValue()){
                        mViewModel.getIsWorkingState().setValue(false);
                    }
                }
            }
        }else  if (messageEvent.getCode() == Const.TCP_CONNECT_STATUS) {
//            boolean isConnect = (Boolean) messageEvent.getData();
//            mBinding.npInfo.setText(isConnect ? "已连接" : "未连接");
        }else if (messageEvent.getCode() == Const.EVENTBUS_HANDLE_STATE) {
            DeviceStatus handleState = (DeviceStatus) messageEvent.getData();
            if (!handleState.isNPressureHandleOnline()) {
                mViewModel.saveDataToFile("np:handle disconnect");
                mViewModel.resetState();
                finish();
            }
        }else if (messageEvent.getCode() == Const.ADDRESS_FROM_ENERGY_BOARD) {
            if (Boolean.TRUE.equals(mViewModel.getIsAutoNeedleMode().getValue())) {
                if (Boolean.TRUE.equals(mViewModel.getIsWorkingState().getValue())) {
                    BeanFromEnergyBoard beanFromEnergyBoard = (BeanFromEnergyBoard) messageEvent.getData();
                    mViewModel.saveDataToFile("np:energy board working data " + new Gson().toJson(beanFromEnergyBoard));
                }
            }else {
                if (Boolean.TRUE.equals(Boolean.FALSE.equals(mViewModel.getIsStandByState().getValue()))) {
                    BeanFromEnergyBoard beanFromEnergyBoard = (BeanFromEnergyBoard) messageEvent.getData();
                    mViewModel.saveDataToFile("np:energy board working data " + new Gson().toJson(beanFromEnergyBoard));
                }
            }

        }
    }

    final static int COUNTS = 5;// 点击次数
    final static long DURATION = 1000;// 规定有效时间
    long[] mHits = new long[COUNTS];
    private void continuousClick() {
        //每次点击时，数组向前移动一位
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        //为数组最后一位赋值
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        if (mHits[0] >= (SystemClock.uptimeMillis() - DURATION)) {
            mHits = new long[COUNTS];//重新初始化数组
            startActivity(new Intent(this, EngineerActivity.class));
        }
    }

    class ShortcutInfoAdapter extends RecyclerView.Adapter<ShortcutInfoAdapter.InnerViewHolder>{

        List<OperationParams> mOperationParams = new ArrayList<>();
        boolean isStandBy = true;

        @NonNull
        @Override
        public ShortcutInfoAdapter.InnerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            ItemShortcutInfoBinding mBinding = ItemShortcutInfoBinding.inflate(getLayoutInflater());
            return new ShortcutInfoAdapter.InnerViewHolder(mBinding);
        }

        @Override
        public void onBindViewHolder(@NonNull ShortcutInfoAdapter.InnerViewHolder holder, int position) {
            if (mOperationParams.isEmpty()) {
                return;
            }
            holder.mItemView.getRoot().setEnabled(isStandBy);
            OperationParams operationParam = mOperationParams.get(position);
            if (operationParam.isEmpty()) {
                holder.mItemView.itemShortcutInfoName.setBackgroundResource(mShortcutList.get(position));
            }else {
                holder.mItemView.itemShortcutInfoName.setBackgroundResource(mShortcutLList.get(position));
            }

            holder.mItemView.getRoot().setOnClickListener(v -> {
                playClickSound();
                if (Boolean.TRUE.equals(mViewModel.getIsPreMode().getValue())) {
                    mViewModel.saveQuickOperationParam(SPHelper.getCurrentUserInfo(getBaseContext()),position+1);
                    Toast.makeText(getBaseContext(), "保存成功!", Toast.LENGTH_SHORT).show();
                } else {
                    if (!operationParam.isEmpty()) {
                        restoreDataAndParams(operationParam);
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return 5;
        }

        class InnerViewHolder extends RecyclerView.ViewHolder{

            private final ItemShortcutInfoBinding mItemView;

            public InnerViewHolder(@NonNull ItemShortcutInfoBinding itemView) {
                super(itemView.getRoot());
                mItemView = itemView;
            }
        }

        @SuppressLint("NotifyDataSetChanged")
        public void setData(List<OperationParams> shortcutInfo){
            mOperationParams.clear();
            mOperationParams.addAll(shortcutInfo);
            notifyDataSetChanged();
        }

        @SuppressLint("NotifyDataSetChanged")
        public void setIsStandBy(boolean isStandBy){
            this.isStandBy = isStandBy;
            notifyDataSetChanged();
        }
    }

    private void restoreDataAndParams(OperationParams operationParam){
        //                    恢复脉冲/连续相关状态
        mViewModel.getIsIntermittentMode().setValue(operationParam.isIntermittentMode());
        if (operationParam.isIntermittentMode()) {
            mBinding.arcSeekBarIdp.setProgress(operationParam.getIntermittentDischargePulse() - idpOffset);
            mBinding.arcSeekBarIdlp.setProgress(operationParam.getIntermittentDischargeLowLevelPeriod() - idlpOffset);
            mBinding.arcSeekBarIdhp.setProgress(operationParam.getIntermittentDischargeHighLevelPeriod() - idhpOffset);
        }else {
            mViewModel.getContinuousDischargePeriod().setValue(operationParam.getContinuousDischargePeriod());
            mViewModel.getContinuousDischargePosition().setValue(operationParam.getContinuousDischargePosition());
            mBinding.npWheelLeftPeriod.setSelectedItemPosition(operationParam.getContinuousDischargePosition());
        }
//                    恢复频率相关状态
        mViewModel.getFrequency().setValue(operationParam.getFreq());
        mBinding.arcSeekBarEnergy.setProgress(operationParam.getPower() - energyOffset);

//                    恢复是否自动出针相关参数  该参数不用管
//                        mViewModel.getIsAutoNeedleMode().setValue(operationParam.isAutoNeedle());
//                        mViewModel.getInterval().setValue(operationParam.getInterval());
//                        switch (operationParam.getInterval()) {
//                            case 0: mViewModel.getIndex().setValue(0);break;
//                            case 500: mViewModel.getIndex().setValue(1);break;
//                            case 1000:mViewModel.getIndex().setValue(3); break;
//                            case 2000: mViewModel.getIndex().setValue(4);break;
//                        }
//                    恢复刺入深度
        mViewModel.getDepth().setValue(operationParam.getDepth());
        mViewModel.getDepthPosition().setValue(operationParam.getDepthPosition());
        mBinding.npWheelRightDepth.setSelectedItemPosition(operationParam.getDepthPosition());
//        Log.e("12121", operationParam.getDepth()+"setSelectedItemPosition2:"+operationParam.getDepthPosition() );

    }
    private void
    showErrMsg(String errInfo){
        mBinding.npInfo.setText(errInfo);
        if (!errInfo.isEmpty()) {
            AnimUtils.startBlink(mBinding.npInfo);
        }
    }

}